<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" :canFullscreen="false" @ok="handleSubmit" width="400px" :minHeight="40">
    <div style="padding-top: 20px">
      <BasicForm @register="registerForm" />
    </div>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { FormSchema } from '/@/components/Table';
  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);
  const oldValue = ref<any>({});

  const formSchema: FormSchema[] = [
    {
      field: 'name',
      label: '',
      component: 'Input',
      dynamicRules: () => {
        return [{ required: true, message: '请输入组合名称!' }];
      },
      componentProps: ({ formActionType, schema, formModel }) => {
        return {
          placeholder: '请输入组合名称',
        };
      },
      colProps: {
        xs: 24,
        sm: 24,
      },
      disabledLabelWidth: true,
    },
  ];

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate, updateSchema }] = useForm({
    labelWidth: 0,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      // 编辑模式下禁用id字段
      //updateSchema({ field: 'id', dynamicDisabled: true });
      oldValue.value = data.record;
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    }
  });

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '创建新组合' : '修改组合名称'));

  //表单提交事件
  async function handleSubmit() {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, oldValue: oldValue.value?.name, newValue: values.name });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
